import React, { useState, memo, useEffect, useRef } from 'react';
import { Table, Dialog, Button, Row, Avatar, Form, Col, Input, Select, Tag } from 'tdesign-react';
import { useAppDispatch, useAppSelector } from 'modules/store';
import SearchForm from './components/SearchForm';

import './index.module.less';
import classnames from 'classnames';
import CommonStyle from '../../../styles/common.module.less';
import { OSS_PREFIX } from '../../../configs/oss';
import { MessagePlugin } from 'tdesign-react/es/message/Message';
import FormItem from 'tdesign-react/es/form/FormItem';
import { TdTagProps } from 'tdesign-react/es/tag/type';
import { FormInstanceFunctions } from 'tdesign-react/es/form/type';
import { clearPageState, getList, selectGoodsListSelect } from 'modules/goods';
import { deleteGoods, updateGoods } from 'api/goods';
import { getGoodsTypeList } from 'api/goodsType';

interface tmpGoodsType {
  id: string;
  typeName: string;
}

const { Option } = Select;

export const SelectTable = () => {
  const formRef = useRef<FormInstanceFunctions>();
  const dispatch = useAppDispatch();
  const pageState = useAppSelector(selectGoodsListSelect);
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const [updateVisible, setUpdateVisible] = useState(false);
  const { loading, contractList, current, size, total } = pageState;
  const [delUserId, setDelUserId] = useState(0);
  const [updateUserId, setUpdateUserId] = useState(0);
  useEffect(() => {
    dispatch(
      getList({
        size: pageState.size,
        current: pageState.current,
      }),
    );
    return () => {
      dispatch(clearPageState());
    };
  }, []);
  const [goodsType, setGoodsType] = useState<tmpGoodsType[]>([]);
  useEffect(() => {
    getGoodsTypeList({}).then((res) => {
      const data = res.data.map((v) => {
        const tmp: tmpGoodsType = { id: v.id, typeName: v.typeName };
        return tmp;
      });
      setGoodsType(data);
    });
  }, []);

  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  function rehandleClickOp(record: any) {
    setUpdateUserId(record.row.id);
    setUpdateVisible(true);
    console.log(record);
  }

  const isUndefined = (data: any) => {
    // eslint-disable-next-line no-restricted-syntax
    for (const key in data) {
      if (key !== 'id' && data[key] !== undefined) {
        return false;
      }
    }
    return true;
  };
  async function updateHandleConfirm() {
    const updateValue = formRef?.current?.getFieldsValue?.(true) as any;
    console.log(updateValue);
    if (isUndefined(updateValue)) {
      await MessagePlugin.error('不能不填写信息修改');
      setUpdateVisible(false);
      return;
    }
    updateValue.id = String(updateUserId);
    const res = await updateGoods(updateValue);
    if (res.data) {
      await MessagePlugin.success(`修改${res.msg}`);
    } else {
      await MessagePlugin.error(`修改${res.msg}`);
    }
    formRef?.current?.reset();
    dispatch(
      getList({
        size: pageState.size,
        current: pageState.current,
      }),
    );
    setUpdateVisible(false);
  }

  function updateHandleClose() {
    setUpdateVisible(false);
  }

  function handleClickDelete(record: any) {
    setVisible(true);
    setDelUserId(record.row.id);
    console.log(record);
  }

  function handleClose() {
    setVisible(false);
  }

  async function handleConfirm() {
    if (delUserId === 0) {
      return;
    }
    const res = await deleteGoods(delUserId);
    if (res.data) {
      MessagePlugin.success(`删除${res.msg}`);
    } else {
      MessagePlugin.error(`删除${res.msg}`);
    }
    dispatch(
      getList({
        size: pageState.size,
        current: pageState.current,
      }),
    );
    setVisible(false);
  }

  return (
    <>
      <Row justify='start' style={{ marginBottom: '20px' }}>
        <SearchForm
          onSubmit={async (value) => {
            console.log(value);
          }}
          onCancel={() => {}}
        />
      </Row>
      <Table
        loading={loading}
        data={contractList}
        columns={[
          {
            title: '商品名称',
            fixed: 'left',
            align: 'left',
            ellipsis: true,
            width: 100,
            colKey: 'name',
          },
          {
            title: '图片',
            fixed: 'left',
            align: 'center',
            ellipsis: true,
            width: 200,
            colKey: 'picture',
            cell(record) {
              return record.row.picture === null || record.row.picture === '' ? (
                <>
                  <Avatar size='100px' shape='round'>
                    {'无商品图片'}
                  </Avatar>
                </>
              ) : (
                <>
                  <Avatar size='100px' shape='round' image={`${OSS_PREFIX}${record.row.picture}`}></Avatar>
                </>
              );
            },
          },
          {
            title: '编号',
            width: 200,
            ellipsis: true,
            colKey: 'id',
            align: 'center',
          },
          {
            title: '类别',
            width: 100,
            ellipsis: true,
            colKey: 'typeKey',
            cell(record) {
              const target = goodsType.find((v) => v.id === record.row.typeKey) as tmpGoodsType;
              const idx = goodsType.indexOf(target);
              const theme: TdTagProps['theme'][] = ['primary', 'default', 'success'];
              return <Tag theme={theme[idx % theme.length]}>{target?.typeName}</Tag>;
            },
          },
          {
            title: '价格',
            width: 140,
            ellipsis: true,
            colKey: 'price',
          },
          {
            title: '库存',
            width: 150,
            ellipsis: true,
            colKey: 'account',
          },
          {
            title: '描述',
            width: 200,
            ellipsis: true,
            colKey: 'description',
            cell(record) {
              const desc = record.row.description;
              return desc === null || desc === '' ? '无' : desc;
            },
          },
          {
            align: 'left',
            fixed: 'right',
            width: 200,
            colKey: 'op',
            title: '操作',
            cell(record) {
              return (
                <>
                  <Button
                    theme='primary'
                    variant='text'
                    onClick={() => {
                      rehandleClickOp(record);
                    }}
                  >
                    修改
                  </Button>
                  <Button
                    theme='primary'
                    variant='text'
                    onClick={() => {
                      handleClickDelete(record);
                    }}
                  >
                    删除
                  </Button>
                </>
              );
            },
          },
        ]}
        rowKey='index'
        selectedRowKeys={selectedRowKeys}
        hover
        onSelectChange={onSelectChange}
        pagination={{
          pageSize: size,
          total,
          current,
          showJumper: true,
          onCurrentChange(current, pageInfo) {
            dispatch(
              getList({
                size: pageInfo.pageSize,
                current: pageInfo.current,
              }),
            );
          },
          onPageSizeChange(size) {
            dispatch(
              getList({
                size,
                current: 1,
              }),
            );
          },
        }}
      />
      <Dialog header='确认删除当前所选商品？' onConfirm={handleConfirm} visible={visible} onClose={handleClose}>
        <p>删除后的所有商品信息将被清空,且无法恢复</p>
      </Dialog>
      <Dialog confirmOnEnter onConfirm={updateHandleConfirm} visible={updateVisible} onClose={updateHandleClose}>
        <Form ref={formRef} colon labelWidth={90}>
          <FormItem label='编号' name='id'>
            <Input disabled placeholder={updateUserId.toString()} />
          </FormItem>
          <FormItem label='名称' name='name'>
            <Input placeholder='请输入商品名称' />
          </FormItem>
          <FormItem label='价格' name='price'>
            <Input placeholder='请输入商品价格' />
          </FormItem>
          <FormItem label='类别' name='typeKey'>
            <Select placeholder='请选择商品类型'>
              {goodsType.map((v, idx) => (
                <Option key={idx} label={v.typeName} value={v.id} />
              ))}
            </Select>
          </FormItem>
          <FormItem label='描述' name='description'>
            <Input placeholder='请输入商品描述' />
          </FormItem>
          <FormItem label='库存' name='account'>
            <Input placeholder='请输入商品库存' />
          </FormItem>
        </Form>
      </Dialog>
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
